import { _decorator, Component, Prefab, instantiate, Node } from 'cc';
const { ccclass, property } = _decorator;
import { Config } from '../Config';
import { UserGlobal } from '../Globals/UserGlobal';

@ccclass('AdoptManager')
export class AdoptManager extends Component {
    @property({ type: Prefab })
    public adoptPrfb: Prefab | null = null;

    private lands: readonly Node[];

    start() {
        this.lands = this.node.parent.parent.children;

        this.adoptInit();
    }

    adoptInit() {
        let adoptNum = UserGlobal.instance._landNumber + 1;

        if (adoptNum >= 1 && adoptNum <= 5) {
            setTimeout((adoptNum) => {
                for (let i = 0; i < this.lands.length; i++) {
                    let name = this.lands[i].name;
                    let num = parseInt(name.substring(4));
                    if (num == adoptNum) {
                        let node = instantiate(this.adoptPrfb);
                        this.lands[i].addChild(node);
                        node.on(Node.EventType.TOUCH_START, this.onAdoptButtonClicked, node);
                        node.setPosition(0, 0);
                    }
                }
            }, adoptNum * 100, adoptNum);
        }
    }

    onAdoptButtonClicked() {
        let config = new Config();
        window.location.href = config.adoptUrl;
    }
}

